<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\common\Auth;
use plugin\admin\app\common\Util;
use plugin\admin\app\model\GoodsActivityRelation;
use plugin\admin\app\model\ShoppingCart;
use plugin\admin\app\model\traits\Relationshipable;
use support\Request;
use support\Response;
use plugin\admin\app\model\GoodsActivity;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 商品活动 
 */
class GoodsActivityController extends Crud
{
    protected $relationTable = '';

    protected $relationField = '';

    /**
     * @var GoodsActivity
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new GoodsActivity;
        $this->relationTable = new GoodsActivityRelation;
        $this->relationField = 'activity_id';
    }

    public function add(Request $request)
    {
        $ids = (array)$request->post('third_party_id', []);
        $id = $request->post('id');

        $relation = (new $this->relationTable)->where($this->relationField, $id)->get()->toArray();
        $goodsIds = array_column($relation, 'goods_id');

        $goodsIds = array_diff($ids, $goodsIds);

        if (count($goodsIds) > 0) {
            $insertData = [];

            foreach ($goodsIds as $goodsId) {
                $insertData[] = [
                    'goods_id' => $goodsId,
                    $this->relationField => $id
                ];
            }

            (new $this->relationTable)->insert($insertData);

            ShoppingCart::whereIn('goods_id', $goodsIds)->delete();
        }

        return $this->json(0, '成功');
    }

    public function remove(Request $request)
    {
        $ids = (array)$request->post('third_party_id', []);
        $id = $request->post('id');

        (new $this->relationTable)->where($this->relationField, $id)->whereIn('goods_id', $ids)->delete();

        return $this->json(0, '成功');
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('goods-activity/index');
    }

    protected function insertInput(Request $request): array
    {
        $data = $this->inputFilter($request->post());
        $password_filed = 'password';
        if (isset($data[$password_filed])) {
            $data[$password_filed] = Util::passwordHash($data[$password_filed]);
        }

        if (!Auth::isSupperAdmin() && $this->dataLimit) {
            if (!empty($data[$this->dataLimitField])) {
                $admin_id = $data[$this->dataLimitField];
                if (!in_array($admin_id, Auth::getScopeAdminIds(true))) {
                    throw new BusinessException('无数据权限');
                }
            }
        }

        $data['start_time'] = strtotime($data['start_time']);
        $data['end_time'] = strtotime($data['end_time']);

        $this->check($data);

        return $data;
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('goods-activity/insert');
    }

    protected function updateInput(Request $request): array
    {
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($request->post());
        if (!Auth::isSupperAdmin() && $this->dataLimit && !empty($data[$this->dataLimitField])) {
            $admin_id = $data[$this->dataLimitField];
            if (!in_array($admin_id, Auth::getScopeAdminIds(true))) {
                throw new BusinessException('无数据权限');
            }
        }
        $password_filed = 'password';
        if (isset($data[$password_filed])) {
            // 密码为空，则不更新密码
            if ($data[$password_filed] === '') {
                unset($data[$password_filed]);
            } else {
                $data[$password_filed] = Util::passwordHash($data[$password_filed]);
            }
        }

        $data['start_time'] = strtotime($data['start_time']);
        $data['end_time'] = strtotime($data['end_time']);

        $this->check($data);

        unset($data[$primary_key]);
        return [$id, $data];
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('goods-activity/update');
    }

    protected function formatNormal($items, $total): Response
    {
        foreach ($items as $key=>$item) {
            $items[$key]['status_text'] = GoodsActivity::getStatusText($item);
            $items[$key]['start_time'] = date('Y-m-d H:i:s', $item['start_time']);
            $items[$key]['end_time'] = date('Y-m-d H:i:s', $item['end_time']);

            $items[$key]['type_text'] = GoodsActivity::TYPE_TEXT[$item['type']];
        }

        return json(['code' => 0, 'msg' => 'ok', 'count' => $total, 'data' => $items]);
    }

    public function delete(Request $request): Response
    {
        $ids = $this->deleteInput($request);
        $this->doDelete($ids);

        GoodsActivityRelation::whereIn('activity_id', $ids)->delete();

        return $this->json(0);
    }

    public function check($data)
    {
        if ($data['start_time'] >= $data['end_time']) {
            throw new \Exception('开始时间不能大于结束时间');
        }

        if ($data['end_time'] < time()) {
            throw new \Exception('结束时间不能小于当前时间');
        }

        if (!empty($data['id'])) {
            $activities = GoodsActivity::where('id', '<>', $data['id'])->get()->toArray();
        } else {
            $activities = GoodsActivity::all()->toArray();
        }

        $message = '活动时间不能与其它活动重叠，一个时间段只有一个活动生效';
        foreach ($activities as $activity) {
            if ($activity['start_time'] < $data['start_time'] && $activity['end_time'] > $data['start_time']) {
                throw new \Exception($message);
            }

            if ($activity['start_time'] < $data['end_time'] && $activity['end_time'] > $data['end_time']) {
                throw new \Exception($message);
            }

            if ($activity['start_time'] > $data['start_time'] && $activity['end_time'] < $data['end_time']) {
                throw new \Exception($message);
            }
        }
    }

}
